package com.bgba.oer;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.rpc.ServiceException;

import com.bgba.oer.service.ProjectService;
import com.bgba.oer.service.RegistryUserService;
import com.bgba.oer.sharepoint.RequirementSharepoint;
import com.flashline.registry.openapi.base.APIValidationException;
import com.flashline.registry.openapi.base.OpenAPIException;
import com.flashline.registry.openapi.entity.AuthToken;
import com.flashline.registry.openapi.entity.Asset;
import com.flashline.registry.openapi.entity.Extraction;
import com.flashline.registry.openapi.entity.Project;
import com.flashline.registry.openapi.entity.ProjectEntities;
import com.flashline.registry.openapi.entity.RegistryUser;
import com.flashline.registry.openapi.query.ProjectCriteria;
import com.flashline.registry.openapi.service.v300.FlashlineRegistry;
import
com.flashline.registry.openapi.service.v300.FlashlineRegistryServiceLocator;
public class ProjectImporter {
	
	
	
	
	public static void main(String pArgs[]) throws ServiceException, ParserConfigurationException, SAXException, IOException  {

		System.out.println("======================== ");
		String urlConnectionLogin = "http://desasoa01/oer/services/FlashlineRegistry?WSDL";
		String username = " L0269239";
		String password = "finde2011";
		/*
		String urlConnectionLogin = "http://172.17.1.10:8101/oer/services/FlashlineRegistry?WSDL";
		String username = " admin";
		String password = "admin123";
		 */
		///////////////////////////////////////////////////////////
		// Connect to Oracle Enterprise Repository
		///////////////////////////////////////////////////////////
		URL lURL = null;
		lURL = new URL(urlConnectionLogin);
		FlashlineRegistry repository = new FlashlineRegistryServiceLocator().getFlashlineRegistry(lURL);

		///////////////////////////////////
		// Login to OER
		///////////////////////////////////
		AuthToken authToken = repository.authTokenCreate(username, password);

		
		////////////////////////////////////////////////////////
		// Parse XML de Requerimientos exportado de SharePoint
		////////////////////////////////////////////////////////
		
		List<RequirementSharepoint> requirements = parseRequirementXml();
		
		for (RequirementSharepoint requirementSharepoint : requirements) {
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("===== req ID ="+requirementSharepoint.getId());
			System.out.println("===== req Number ="+requirementSharepoint.getNumber());
			System.out.println("===== req Name ="+requirementSharepoint.getName());
			System.out.println("===== req UserId ="+requirementSharepoint.getUserId());
			
			Project oerProject = new Project();
			oerProject.setName(requirementSharepoint.getNumber() + " - "+ requirementSharepoint.getName());
			oerProject.setDisplayName(requirementSharepoint.getName());
			oerProject.setDescription(requirementSharepoint.getName());

			long registryUserOerId = 0;
			if (requirementSharepoint.getUserId() > 0){ 
				
				String usernameOer = ResourceBundleHelper.getInstance().getSharePointUserName(String.valueOf(requirementSharepoint.getUserId()));				
				System.out.println("==== usernameOer="+usernameOer);
				
				RegistryUser registryUserOer = RegistryUserService.searchRegistryUser(repository, authToken, usernameOer);
				System.out.println("============ registryUserOer.getID="+registryUserOer.getID());
				System.out.println("============ registryUserOer.getEmail="+registryUserOer.getEmail());
				
				registryUserOerId = registryUserOer.getID();
			}
			
			ProjectService.addProject(repository, authToken, oerProject, registryUserOerId);
			System.out.println("============ #################################### ###############################");
			System.out.println("============ #################################### SE HA CREADO UN PROJECT");
			System.out.println("============ #################################### ###############################");

			
		}
		/*
		Project myProject = new Project();
		//myProject.setName("NEW_PROJECT_NAME");
		//myProject.setDisplayName("The New Proyect Name");
		
		ProjectService.addProject(repository, authToken, myProject, 111111111);
		*/

	}


	public static List<RequirementSharepoint>  parseRequirementXml() throws ParserConfigurationException, SAXException, IOException {

			List<RequirementSharepoint> requirementList = new ArrayList<RequirementSharepoint>();
			
			File file = new File("/home/alex/galicia/oer_migracion/OER/Requerimientos.xml");
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();
			System.out.println("Root element " + doc.getDocumentElement().getNodeName());
			NodeList nodeLst = doc.getElementsByTagName("Requerimientos");
			System.out.println("Requerimientos");

			for (int s = 0; s < nodeLst.getLength(); s++) {

				Node fstNode = nodeLst.item(s);

				if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

					Element fstElmnt = (Element) fstNode;
					NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("ID");
					Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
					//System.out.println("== fstNmElmnt.getTagName="+fstNmElmnt.getTagName());
					NodeList fstNm = fstNmElmnt.getChildNodes();
					String requiIdString =  ((Node) fstNm.item(0)).getNodeValue();
					System.out.println("\nRequerimiento ID: "+requiIdString);  

					NodeList fstNmElmntLstNumero = fstElmnt.getElementsByTagName("Número");
					Element fstNmElmntNumero = (Element) fstNmElmntLstNumero.item(0);
					//System.out.println("== fstNmElmnt.getTagName="+fstNmElmntDescrip.getTagName());
					NodeList fstNmNumero = fstNmElmntNumero.getChildNodes();
					String requiNumero = ((Node) fstNmNumero.item(0)).getNodeValue();
					System.out.println("Número: " + requiNumero);
					
					NodeList fstNmElmntLstDescrip = fstElmnt.getElementsByTagName("Descripción");
					Element fstNmElmntDescrip = (Element) fstNmElmntLstDescrip.item(0);
					//System.out.println("== fstNmElmnt.getTagName="+fstNmElmntDescrip.getTagName());
					NodeList fstNmDescrip = fstNmElmntDescrip.getChildNodes();
					String requiDescription = ((Node) fstNmDescrip.item(0)).getNodeValue();
					System.out.println("Descripción: " + requiDescription);

					NodeList fstNmElmntLstResp = fstElmnt.getElementsByTagName("Responsable");
					//System.out.println("=== fstNmElmntLstResp Respon"+ fstNmElmntLstResp);
					NodeList fstNmElmntLstRespValue = fstElmnt.getElementsByTagName("Value");
					Element fstNmElmntRespValue = (Element) fstNmElmntLstRespValue.item(0);
					//System.out.println("=== fstNmElmntRespValue ="+fstNmElmntRespValue);
					String requiUserSharePointIdString = "0";
					if (fstNmElmntRespValue != null){
						//System.out.println("== fstNmElmnt.getTagName="+fstNmElmntRespValue.getTagName());
						NodeList fstNmRespValue = fstNmElmntRespValue.getChildNodes();
						requiUserSharePointIdString = ((Node) fstNmRespValue.item(0)).getNodeValue();
					}
					System.out.println("Responsable Value ID: "  + requiUserSharePointIdString);

					/*
					NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Responsable");
					Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
					NodeList lstNm = lstNmElmnt.getChildNodes();
					System.out.println("Estado : " + ((Node) lstNm.item(0)).getNodeValue());
					 */
					
					int reqId = Integer.parseInt(requiIdString);
					//int reqNumero = Integer.parseInt(requiNumero);
					int reqUserId = Integer.parseInt(requiUserSharePointIdString);
					RequirementSharepoint requirement = new RequirementSharepoint(reqId, requiNumero, requiDescription, reqUserId);
					//add the requirement to list
					requirementList.add(requirement);

				}
			}
			
			return requirementList;
	}


	
}
